// vConsole Network面板快速调试脚本
// 在浏览器控制台中直接运行

(function() {
    'use strict';
    
    console.log('🚀 开始vConsole Network调试...');
    
    // 1. 检查vConsole状态
    function checkVConsoleStatus() {
        const status = {
            VConsoleDefined: typeof VConsole !== 'undefined',
            vConsoleInstance: !!window.vconsole,
            protocol: location.protocol,
            hostname: location.hostname,
            userAgent: navigator.userAgent.substring(0, 100) + '...'
        };
        
        console.log('📊 vConsole状态:', status);
        return status;
    }
    
    // 2. 强制初始化vConsole
    function forceInitVConsole() {
        if (window.vconsole) {
            console.log('🔄 销毁现有vConsole实例');
            window.vconsole.destroy();
        }
        
        console.log('🆕 创建新的vConsole实例');
        window.vconsole = new VConsole({
            theme: 'dark',
            defaultPlugins: ['system', 'network', 'element', 'storage'],
            maxLogNumber: 1000,
            onReady: function() {
                console.log('✅ vConsole已准备就绪');
                setTimeout(() => {
                    if (window.vconsole.showTab) {
                        window.vconsole.showTab('network');
                        console.log('🌐 已切换到Network标签');
                    }
                }, 500);
            }
        });
        
        return window.vconsole;
    }
    
    // 3. 测试网络请求
    function testNetworkRequests() {
        console.log('🧪 开始网络请求测试...');
        
        // 测试1：简单XHR
        const xhr1 = new XMLHttpRequest();
        xhr1.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');
        xhr1.onload = () => console.log('✅ XHR测试1完成');
        xhr1.onerror = () => console.log('❌ XHR测试1失败');
        xhr1.send();
        
        // 测试2：Fetch请求
        fetch('https://jsonplaceholder.typicode.com/posts/2')
            .then(r => r.json())
            .then(d => console.log('✅ Fetch测试完成:', d.id))
            .catch(e => console.log('❌ Fetch测试失败:', e.message));
        
        // 测试3：POST请求
        fetch('https://jsonplaceholder.typicode.com/posts', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ title: '测试', body: '内容', userId: 1 })
        })
        .then(r => r.json())
        .then(d => console.log('✅ POST测试完成:', d.id))
        .catch(e => console.log('❌ POST测试失败:', e.message));
        
        // 测试4：错误请求
        fetch('https://jsonplaceholder.typicode.com/posts/999999')
            .then(r => {
                if (!r.ok) throw new Error('HTTP错误: ' + r.status);
                return r.json();
            })
            .catch(e => console.log('✅ 错误测试完成:', e.message));
    }
    
    // 4. 修复XMLHttpRequest监控
    function fixXMLHttpRequest() {
        console.log('🔧 修复XMLHttpRequest监控...');
        
        const originalXHR = window.XMLHttpRequest;
        const originalFetch = window.fetch;
        
        // 重写XMLHttpRequest
        window.XMLHttpRequest = function() {
            const xhr = new originalXHR();
            const originalOpen = xhr.open;
            const originalSend = xhr.send;
            
            xhr.open = function(method, url, ...args) {
                console.log(`🌐 XHR请求: ${method} ${url}`);
                return originalOpen.apply(xhr, [method, url, ...args]);
            };
            
            xhr.send = function(data) {
                console.log(`📤 XHR发送: ${data ? data.length : 0}字节`);
                return originalSend.call(xhr, data);
            };
            
            return xhr;
        };
        
        // 重写fetch
        window.fetch = function(url, options = {}) {
            console.log(`🌐 Fetch请求: ${options.method || 'GET'} ${url}`);
            return originalFetch.call(window, url, options);
        };
        
        console.log('✅ XMLHttpRequest监控已修复');
    }
    
    // 5. 完整调试流程
    function runFullDebug() {
        console.log('🎯 开始完整调试流程...');
        
        // 步骤1：检查状态
        checkVConsoleStatus();
        
        // 步骤2：强制初始化
        forceInitVConsole();
        
        // 步骤3：修复监控
        fixXMLHttpRequest();
        
        // 步骤4：等待1秒后测试
        setTimeout(() => {
            testNetworkRequests();
        }, 1000);
        
        console.log('🎉 调试流程已启动，请查看Network面板');
    }
    
    // 6. 快捷命令
    const commands = {
        check: checkVConsoleStatus,
        init: forceInitVConsole,
        test: testNetworkRequests,
        fix: fixXMLHttpRequest,
        debug: runFullDebug
    };
    
    // 7. 添加到全局
    window.vconsoleDebug = commands;
    
    // 8. 使用说明
    console.log('📋 使用方法：');
    console.log('  vconsoleDebug.check()  - 检查vConsole状态');
    console.log('  vconsoleDebug.init()   - 重新初始化vConsole');
    console.log('  vconsoleDebug.test()   - 测试网络请求');
    console.log('  vconsoleDebug.fix()    - 修复网络监控');
    console.log('  vconsoleDebug.debug()  - 完整调试流程');
    
    // 9. 自动运行基础检查
    setTimeout(() => {
        console.log('🔍 自动检查中...');
        checkVConsoleStatus();
    }, 100);
    
    console.log('✨ vConsole调试脚本已加载！');
    
})();